package com.chy.blog_server.modular.sharCore;

import cn.hutool.core.date.ChineseDate;
import com.chy.blog_server.core.util.DateUtil;
import com.chy.blog_server.modular.web.service.IBoMarkDateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时器
 * @Component注解用于对那些比较中立的类进行注释；
 * 相对与在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注释
 */
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
@ConditionalOnExpression("#{'pro'.equals(environment['spring.profiles.active'])}") //正式环境才开启
public class ScheduleTask {

    Logger logger = LoggerFactory.getLogger(ScheduleTask.class);

    @Autowired
    private IBoMarkDateService boMarkDateService;

    /**
     * 定时器-刷新纪念日提醒 记录年份为下一年
     */
    @Async
//    @Scheduled(cron = "0/30 * * * * ?") //20秒
    @Scheduled(cron = "0 0 8 * * ?")  //每天8点开始执行0 0 8 * * ?
    public void refreshMarkDateNextYear(){
        logger.info(">>>>>>>>>定时器-刷新纪念日年份为下一年-开始执行");
        try{
            //使用hutool工具类将当前日期转成农历
            String currentDate = DateUtil.getSystemDate(); //当前日期
            ChineseDate chineseDate = new ChineseDate(DateUtil.getDateUtileString(currentDate));
            int chineseYear = chineseDate.getChineseYear();
            String chineseMonth = chineseDate.getChineseMonth();
            String chineseDay = chineseDate.getChineseDay();
            int month = chineseDate.getMonth();
            int date = chineseDate.getDay();
            String chinesDate = chineseYear + "-" + month + "(" + chineseMonth + ")-" + date + "(" + chineseDay + ")";
            logger.info(">>>>>>>>>定时器-刷新纪念日年份为下一年-当前日期：{}，对应农历日期：{}", currentDate, chinesDate);
            //一月初一则执行刷新年份
            if(month == 1 && date == 1){
                boMarkDateService.refreshNextYear(null);
                logger.info(">>>>>>>>>定时器-刷新纪念日年份为下一年-刷新成功");
            }
            logger.info(">>>>>>>>>定时器-刷新纪念日年份为下一年-执行结束");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
